Information about variables

Table of contents

Problem

You want to find information about variables.

Solution

Here are some sample variables to work with in the examples below:

x <- 6
n <- 1:4
let <- LETTERS[1:4]
df <- data.frame(n, let)

Information about existence

# List currently defined variables
ls()
#  "df"  "let" "n"   "x"  

# Check if a variable named "x" exists
exists("x")
#  TRUE

# Check if "y" exists
exists("y")
#  FALSE

# Delete variable x
rm(x)
x
# Error: object "x" not found

Information about size/structure

# Get information about structure
str(n)
#  int [1:4] 1 2 3 4

str(df)
# 'data.frame': 4 obs. of  2 variables:
#  $ n  : int  1 2 3 4
#  $ let: Factor w/ 4 levels "A","B","C","D": 1 2 3 4

# Get the length of a vector
length(n)
#  4

# Length probably doesn't give us what we want here:
length(df)
#  2

# Number of rows
nrow(df)
#  4

# Number of columns
ncol(df)
#  2

# Get rows and columns
dim(df)
#  4 2